<!-- src/views/VmInstanceList.vue (或您的主组件文件名) -->
<template>
  <div class="vm-panel panel">
    <h1>虚拟机实例列表</h1>
    <!-- 虚拟机实例表格 -->
    <el-table :data="instancesWithMetrics" border style="width: 100%" @row-click="handleRowClick" highlight-current-row>
      <el-table-column prop="id" label="ID" width="60" align="center" fixed></el-table-column>
      <el-table-column prop="hostname" label="主机名" min-width="150"></el-table-column>
      <el-table-column prop="ip" label="IP 地址" width="130"></el-table-column>
      <el-table-column prop="os" label="操作系统" min-width="180"></el-table-column>

      <!-- 使用引入的 MiniChart 组件 -->
      <el-table-column label="CPU (%)" width="140" align="center">
        <template #default="scope">
          <MiniChart :data="scope.row.cpuHistory" :current="scope.row.cpuUsage" color="#409EFF" />
        </template>
      </el-table-column>
      <el-table-column label="内存 (%)" width="140" align="center">
        <template #default="scope">
          <MiniChart :data="scope.row.memoryHistory" :current="scope.row.memoryUsage" color="#E6A23C" />
        </template>
      </el-table-column>
      <el-table-column label="存储 (%)" width="140" align="center">
        <template #default="scope">
          <MiniChart :data="scope.row.diskHistory" :current="scope.row.diskUsage" color="#F56C6C" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 展开详情 -->
    <el-collapse v-model="activeCollapse" class="mt-4">
      <el-collapse-item title="详细信息" name="details">
        <div v-if="selectedInstance" class="instance-details">
          <p><strong>ID:</strong> {{ selectedInstance.id }}</p>
          <p><strong>主机名:</strong> {{ selectedInstance.hostname }}</p>
          <p><strong>IP 地址:</strong> {{ selectedInstance.ip }}</p>
          <p><strong>操作系统:</strong> {{ selectedInstance.os }}</p>

          <div v-if="metricsLoading" class="loading">加载中...</div>
          <div v-else-if="metrics[selectedInstance.id]" class="metrics">
            <p><i class="el-icon-monitor"></i> CPU 使用率：{{ metrics[selectedInstance.id].cpu.toFixed(2) }}%</p>
            <p><i class="el-icon-box"></i> 内存使用率：{{ metrics[selectedInstance.id].memory.toFixed(2) }}%</p>
            <p><i class="el-icon-document"></i> 磁盘使用率：{{ metrics[selectedInstance.id].disk.toFixed(2) }}%</p>
            <p><i class="el-icon-connection"></i> 网络流量：{{ metrics[selectedInstance.id].networkTraffic.toFixed(2) }} Mbps</p>
          </div>
          <div v-else class="no-metrics">无法加载监控数据。</div>
        </div>
        <div v-else class="no-selection">请选择一个实例查看详细信息。</div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
// --- 引入 MiniChart 组件 ---
import MiniChart from '../../../components/Chart/MiniChart.vue'; // 根据您的实际路径调整

// 注意：在实际项目中需要安装并引入 Element Plus 图标
// import { Monitor, Box, Document, Connection } from '@element-plus/icons-vue';

// --- 移除内联的 MiniChart 组件定义 ---

const instances = ref([]);
const metrics = ref({}); // 当前指标
const histories = ref({}); // 历史指标
const selectedInstance = ref(null);
const activeCollapse = ref('');
const metricsLoading = ref(false);

// 计算属性：合并实例、当前指标和历史数据
const instancesWithMetrics = computed(() => {
  return instances.value.map(instance => {
    const metric = metrics.value[instance.id];
    const history = histories.value[instance.id] || { cpu: [], memory: [], disk: [] };

    let cpuUsage = null, memoryUsage = null, diskUsage = null;
    if (metric) {
      cpuUsage = metric.cpu;
      memoryUsage = metric.memory;
      diskUsage = metric.disk;
    }

    return {
      ...instance,
      cpuUsage,
      memoryUsage,
      diskUsage,
      // 传递历史数组的副本
      cpuHistory: [...history.cpu],
      memoryHistory: [...history.memory],
      diskHistory: [...history.disk]
    };
  });
});

// --- 模拟数据生成函数 ---
const osList = ['Ubuntu 20.04 LTS', 'CentOS 8', 'Windows Server 2019', 'Debian 11', 'Rocky Linux 9'];
const generateRandomInstances = (count) => {
  const instanceList = [];
  for (let i = 1; i <= count; i++) {
    const ipParts = Array.from({ length: 4 }, () => Math.floor(Math.random() * 255)).join('.');
    instanceList.push({
      id: i,
      hostname: `vm-host-${i.toString().padStart(3, '0')}`,
      ip: ipParts,
      os: osList[Math.floor(Math.random() * osList.length)],
    });
  }
  return instanceList;
};

const generateRandomMetrics = () => {
  return {
    cpu: Math.random() * 100,
    memory: Math.random() * 100,
    disk: Math.random() * 100,
    networkTraffic: Math.random() * 1000,
  };
};
// --- 模拟数据生成函数结束 ---

// --- 模拟定时更新指标 ---
let updateInterval = null;
const HISTORY_LENGTH = 10;

const initializeHistories = () => {
  instances.value.forEach(instance => {
    if (!histories.value[instance.id]) {
      const initialMetric = generateRandomMetrics();
      metrics.value[instance.id] = initialMetric;

      histories.value[instance.id] = {
        cpu: Array(HISTORY_LENGTH).fill(initialMetric.cpu),
        memory: Array(HISTORY_LENGTH).fill(initialMetric.memory),
        disk: Array(HISTORY_LENGTH).fill(initialMetric.disk)
      };
    }
  });
};

const updateAllMetrics = () => {
  console.log("定时更新所有实例指标...");
  instances.value.forEach(instance => {
    const newMetric = generateRandomMetrics();

    metrics.value[instance.id] = {
      cpu: parseFloat(newMetric.cpu.toFixed(2)),
      memory: parseFloat(newMetric.memory.toFixed(2)),
      disk: parseFloat(newMetric.disk.toFixed(2)),
      networkTraffic: parseFloat(newMetric.networkTraffic.toFixed(2))
    };

    if (!histories.value[instance.id]) {
      histories.value[instance.id] = { cpu: [], memory: [], disk: [] };
    }

    const history = histories.value[instance.id];
    history.cpu.push(parseFloat(newMetric.cpu.toFixed(2)));
    history.memory.push(parseFloat(newMetric.memory.toFixed(2)));
    history.disk.push(parseFloat(newMetric.disk.toFixed(2)));

    if (history.cpu.length > HISTORY_LENGTH) history.cpu.shift();
    if (history.memory.length > HISTORY_LENGTH) history.memory.shift();
    if (history.disk.length > HISTORY_LENGTH) history.disk.shift();

    console.log(`实例 ${instance.id} 指标已更新:`, metrics.value[instance.id]);
  });
};

onMounted(async () => {
  console.log("正在加载虚拟机实例...");
  setTimeout(() => {
    try {
      const mockInstances = generateRandomInstances(8);
      instances.value = mockInstances;
      console.log("虚拟机实例加载成功:", mockInstances);

      initializeHistories();
      updateInterval = setInterval(updateAllMetrics, 3000);

    } catch (err) {
      console.error('生成虚拟机实例失败:', err);
    }
  }, 800);
});

onBeforeUnmount(() => {
  if (updateInterval) {
    clearInterval(updateInterval);
    console.log("已停止定时更新指标。");
  }
});

function handleRowClick(row) {
  console.log("选中实例:", row);
  selectedInstance.value = row;
  activeCollapse.value = 'details';
}
</script>

<style scoped>
.vm-panel {
  padding: 20px;
  max-width: 100%;
  margin: 0 auto;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  box-sizing: border-box;
}

.vm-panel h1 {
  margin-bottom: 20px;
  color: #333;
}

/* 表格列宽调整 */
:deep(.el-table__cell) {
  padding: 4px 0;
}

/* 表格内容居中 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

/* 表格表头居中 */
:deep(.el-table th.el-table__cell > .cell) {
  text-align: center;
}

/* 小曲线图容器的样式已移至 MiniChart.vue */


.instance-details {
  padding: 10px 0;
}

.instance-details p {
  margin: 8px 0;
}

.loading {
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 20px 0;
}

.metrics p {
  margin: 10px 0;
  font-size: 1.05em;
}

.no-selection, .no-metrics {
  color: #666;
  text-align: center;
  padding: 20px 0;
}
</style>